package com.situ.mall.order.controller;

import com.situ.mall.api.product.ProductClient;
import com.situ.mall.common.util.Result;
import com.situ.mall.order.pojo.vo.OrderCategroyCount;
import com.situ.mall.order.pojo.vo.OrderProductCount;
import com.situ.mall.order.service.IOrderItemService;
import com.situ.mall.pojo.entity.order.OrderInfo;
import com.situ.mall.pojo.entity.order.OrderItem;
import com.situ.mall.pojo.entity.product.Category;
import com.situ.mall.pojo.entity.product.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单项信息 前端控制器
 * </p>
 *
 * @author Sun Huijuan
 * @since 2024-10-14
 */
@RestController
@RequestMapping("/order/orderItem")
public class OrderItemController {
	@Autowired
	private IOrderItemService orderItemService;
	@Autowired
	private ProductClient productClient;
	
	@GetMapping("/selectByOrderNo")
	public Result<List<OrderItem>> selectByOrderNo(OrderInfo orderInfo) {
		String orderNo = orderInfo.getOrderNo();
		List<OrderItem> list=orderItemService.selectByOrderNo(orderNo);
		return Result.ok(list);
	}
	
	//【后台管理——统计图表：查询各一级分类销售额】
	@GetMapping("/selectCategoryAmount")
	public Result<List<OrderCategroyCount>> selectCategoryAmount() {
		List<OrderCategroyCount> list=new ArrayList<>();
		//1.将订单已完成的订单详情进行按产品分组统计交易数量【产品ID、销售额】
		List<OrderProductCount> orderProductCountList=orderItemService.selectCategoryAmount();
		//2.遍历列表，通过productId查询product获取一级分类ID
		for(OrderProductCount orderProductCount:orderProductCountList){
			Product product= productClient.selectById(orderProductCount.getProductId()).getData();
			Category category=productClient.selectCategory(product.getCategory1Id()).getData();
			boolean flag=false;
			for (OrderCategroyCount categroyCount:list){
				if ((categroyCount.getCategroy1Name()).equals(category.getName())){
					categroyCount.setTotalAmount(categroyCount.getTotalAmount().add(orderProductCount.getAmount()));
					flag=true;
				}
			}
			if (!flag){
				OrderCategroyCount orderCategroyCount=new OrderCategroyCount();
				orderCategroyCount.setTotalAmount(orderProductCount.getAmount());
				orderCategroyCount.setCategroy1Name(category.getName());
				list.add(orderCategroyCount);
			}
		}
		return Result.ok(list);
	}

}

